package com.forsythia.sns.action;

import java.util.Map;

import org.apache.struts2.interceptor.CookiesAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.forsythia.sns.Constants;
import com.forsythia.sns.service.UserService;
import com.forsythia.sns.to.UserTO;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements SessionAware, RequestAware, CookiesAware {

    public boolean isLogined() {
        if (getSession().get(Constants.SESSION_CURRENT_USER) != null) {
            return true;
        } else {
            String passport = getCookiesMap().get(Constants.COOKIE_PASSPORT);
            String password = getCookiesMap().get(Constants.COOKIE_PASSWORD);
            if (login(passport, password) != null) {
                return true;
            }
        }
        return false;
    }

    protected UserTO login(String passport, String password) {
        UserTO user = userService.getUserByPassport(passport, password);
        if (user != null) {
            getSession().put(Constants.SESSION_CURRENT_USER, user);
        }
        return user;
    }

    protected void putLocaleIntoSession() {
        if (request.containsKey(SESSION_LOCALE_KEY)) {
            session.put(SESSION_LOCALE_KEY, request.get(SESSION_LOCALE_KEY));
        }
    }

    // ////////////////////////////////////////////////////////////////////////////
    protected UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    // ////////////////////////////////////////////////////////////////////////////
    public static final String SESSION_LOCALE_KEY = "request_locale";
    // ////////////////////////////////////////////////////////////////////////////
    private static final long serialVersionUID = -1290691564958190441L;

    private Map<Object, Object> session;
    private Map<Object, Object> request;
    private Map<Object, String> cookie;

    @Override
    public void setSession(Map session) {
        this.session = session;
    }

    public Map<Object, Object> getSession() {
        return this.session;
    }

    @Override
    public void setRequest(Map request) {
        this.request = request;
    }

    public Map<Object, Object> getRequest() {
        return this.request;
    }

    @Override
    public void setCookiesMap(Map cookie) {
        this.cookie = cookie;
    }

    public Map<Object, String> getCookiesMap() {
        return this.cookie;
    }
}
